package fr.curriculumvitae.anthony.stephan.fragments;

import fr.curriculumvitae.anthony.stephan.R;
import fr.curriculumvitae.anthony.stephan.SwipeyTabsActivity;
import fr.curriculumvitae.anthony.stephan.activities.DetailsActivity;
import fr.curriculumvitae.anthony.stephan.pinnedsections.PinnedSectionListView;
import fr.curriculumvitae.anthony.stephan.pinnedsections.PinnedSectionListView.PinnedSectionListAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TrainingsFragment extends ListFragment {
	
	private static final int REQUEST_PROJECT_DETAILS = 1001;
	
	private static Fragment INSTANCE = null;
	
	private static SwipeyTabsActivity fragmentController;
	private static Fragment mLocalContext;
	
	private static final int SECTION_MASTER 	= 0;
	private static final int SECTION_LICENCE 	= 1;
	private static final int SECTION_DUT 		= 2;
	private static final int SECTION_BAC 		= 3;
	
	private static String[] sectionLabels;
	private static String[] formationsLabels;
	private static String[] schoolsLabels;
	private static String[] places;
	private static String[] dates;
	private static String[] links;
	private static String[] linksDisplay;
	private static String[] resumes;
	
	public static Fragment getInstance() {
		if(INSTANCE == null) {
			INSTANCE = new TrainingsFragment();
		} 
		return INSTANCE;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.pinned_head_list, null);
		return root;
	}
	
 	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
 		fragmentController = (SwipeyTabsActivity) getActivity();
 		mLocalContext = this;
 		inflateArrays();
		initializeAdapter();
		initializeListView();
	}
 	
	private void initializeListView() {
	    getListView().setPadding(0, 0, 0, 0);
	    ((PinnedSectionListView)getListView()).setShadowVisible(false);
	}

    private void inflateArrays() {
    	sectionLabels = getResources().getStringArray(R.array.trainings_sections_labels);
    	formationsLabels = getResources().getStringArray(R.array.trainings_formations);
    	schoolsLabels = getResources().getStringArray(R.array.trainings_schools);
    	places = getResources().getStringArray(R.array.trainings_places);
    	dates = getResources().getStringArray(R.array.trainings_dates);
    	links = getResources().getStringArray(R.array.trainings_links);
    	linksDisplay = getResources().getStringArray(R.array.trainings_links_display);
    	resumes = getResources().getStringArray(R.array.trainings_resumes);
    }

    private void initializeAdapter() {
    	SimpleAdapter adapter = new SimpleAdapter(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1);
    	setListAdapter(adapter);
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {  
    	super.onActivityResult(requestCode, resultCode, data);
    	if(requestCode == REQUEST_PROJECT_DETAILS && resultCode == Activity.RESULT_OK) {
    		Bundle extras = data.getExtras();
    		if(data.getExtras() != null) {
    			boolean swipeNeeded = true;
    			int section = extras.getInt("sectionID");
    			int position = extras.getInt("position");
    			switch(section) {
    			case SECTION_MASTER:
    				if(position == 1) {
    					ProductionsFragment.displayProduction(ProductionsFragment.SECTION_PICTURESEDITOR);
    				} else if(position == 3) {
    					ProductionsFragment.displayProduction(ProductionsFragment.SECTION_UPMCONTACT);
    				} else if(position == 4) {
    					ProductionsFragment.displayProduction(ProductionsFragment.SECTION_AVC);
    				} else {
    					swipeNeeded = false;
    				}
    				break;
    			case SECTION_LICENCE:
    				if(position == 2) {
    					ProductionsFragment.displayProduction(ProductionsFragment.SECTION_MANDELBROT);
    				} else {
    					swipeNeeded = false;
    				}
    				break;
    			case SECTION_DUT:
    				if(position == 5) {
    					ProductionsFragment.displayProduction(ProductionsFragment.SECTION_REGULATOR);
    				} else {
    					swipeNeeded = false;
    				}
    				break;
    			case SECTION_BAC:
    				if(position == 1) {
    					ProductionsFragment.displayProduction(ProductionsFragment.SECTION_CLEANER);
    				} else {
    					swipeNeeded = false;
    				}
    				break;
    			}
    			if(swipeNeeded) {
    				fragmentController.swipeToTab(SwipeyTabsActivity.SWIPEY_TAB_PRODUCTIONS);
    			}
    		}
    	}
    }
    
    
      /////////////
     // ADAPTER //
    /////////////
    
	private static class SimpleAdapter extends ArrayAdapter<Training> implements PinnedSectionListAdapter {

        public SimpleAdapter(Context context, int resource, int textViewResourceId) {
            super(context, resource, textViewResourceId);

            final int sectionsNumber = sectionLabels.length;
            prepareSections(sectionsNumber);
            
            int sectionPosition = 0, listPosition = 0;
            
            for(char i=0; i<sectionsNumber; i++) {
                Training section = new Training(Training.SECTION, sectionLabels[i], null, null, null, null, null, null, null);
                section.sectionNumber = i;
                section.sectionPosition = sectionPosition;
                section.listPosition = listPosition++;
                onSectionAdded(section, sectionPosition);
                add(section);
                
                Training item = new Training(Training.ITEM, sectionLabels[i], formationsLabels[i], 
                							 schoolsLabels[i], places[i], dates[i], links[i], linksDisplay[i], resumes[i]);
                item.sectionNumber = i;
                item.sectionPosition = sectionPosition;
                item.listPosition = listPosition++;
                add(item);
                sectionPosition++;
            }
        }

        protected void prepareSections(int sectionsNumber) {
        	/* nothing to do */
        }
        
        protected void onSectionAdded(Training section, int sectionPosition) { 
        	/* nothing to do */
        }

        @Override 
        public View getView(int position, View convertView, ViewGroup parent) {
        	LayoutInflater inflater = (LayoutInflater) fragmentController.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        	View view = null;
        	Training item = getItem(position);
        	
        	if(item.type == Training.SECTION) {
        		view = inflater.inflate(R.layout.layout_header, null);
                ((TextView) view).setText(item.label);
        		switch(item.sectionNumber) {
	        		case SECTION_MASTER:
	        			view.setBackgroundColor(parent.getResources().getColor(R.color.pinnedheader_head_green));
	        			break;
	        		case SECTION_LICENCE:
	        			view.setBackgroundColor(parent.getResources().getColor(R.color.pinnedheader_head_blue));
	        			break;
	        		case SECTION_DUT:
	        			view.setBackgroundColor(parent.getResources().getColor(R.color.pinnedheader_head_violet));
	        			break;
	        		case SECTION_BAC:
	        			view.setBackgroundColor(parent.getResources().getColor(R.color.pinnedheader_head_red));
	        			break;
        		}
        		view.setTag(null);
        		
        	} else if(item.type == Training.ITEM) {
        		view = inflater.inflate(R.layout.layout_row_training, null);
        		TextView tvFormationLabel = (TextView) view.findViewById(R.id.textView_training_formation);
        		TextView tvSchool = (TextView) view.findViewById(R.id.textView_training_school);
        		TextView tvPlace = (TextView) view.findViewById(R.id.textView_training_place);
        		TextView tvDates = (TextView) view.findViewById(R.id.textView_training_dates);
        		TextView tvLink = (TextView) view.findViewById(R.id.textView_training_link);
        		TextView tvSpoiler = (TextView) view.findViewById(R.id.textView_resume_spoiler_text);
        		TextView tvResume = (TextView) view.findViewById(R.id.textView_training_resume);
        		ImageView ivLogo = (ImageView) view.findViewById(R.id.imageView_headband);
        		ImageView ivMoreDetails = (ImageView) view.findViewById(R.id.imageView_more_details);
        		ImageView ivProjects = (ImageView) view.findViewById(R.id.imageView_projects);
        		ImageView ivSpoilerArrow = (ImageView) view.findViewById(R.id.imageView_resume_spoiler_arrow);
        		
        		tvFormationLabel.setText(item.formation);
        		tvSchool.setText(item.school);
        		tvPlace.setText(item.place);
        		tvDates.setText(item.dates);
        		tvResume.setText(item.resume);
        		tvLink.setMovementMethod(LinkMovementMethod.getInstance());
        		tvLink.setText(Html.fromHtml("<a href=\'"+item.link+"\'>"+item.linkDisplay+"</a>"));
        		
        		switch(item.sectionNumber) {
	        		case SECTION_MASTER:
	        			ivLogo.setImageDrawable(fragmentController.getResources().getDrawable(R.drawable.im_headband_upmc));
	        			break;
	        		case SECTION_LICENCE:
	        			ivLogo.setImageDrawable(fragmentController.getResources().getDrawable(R.drawable.im_headband_upmc_blue));
	        			break;
	        		case SECTION_DUT:
	        			ivLogo.setImageDrawable(fragmentController.getResources().getDrawable(R.drawable.im_headband_iut_violet));
	        			break;
	        		case SECTION_BAC:
	        			ivLogo.setImageDrawable(fragmentController.getResources().getDrawable(R.drawable.im_headband_lycee_red));
	        			break;
        		}
        		ivMoreDetails.setOnClickListener(new OnMoreDetailsClickListener(item.sectionNumber));
        		ivProjects.setOnClickListener(new OnProjectsClickListener(item.sectionNumber));
        		
        		tvSpoiler.setText(fragmentController.getResources().getString(R.string.display_training_resume));
        		ivSpoilerArrow.setImageDrawable(fragmentController.getResources().getDrawable(R.drawable.ic_arrow_to_right));
        		tvSpoiler.setOnClickListener(new OnResumeSpoilerClickListener(ivSpoilerArrow, tvSpoiler, tvResume));
        	}
        	
            return view;
        }

        @Override 
        public int getViewTypeCount() {
            return 2;
        }

        @Override 
        public int getItemViewType(int position) {
            return getItem(position).type;
        }

        @Override
        public boolean isItemViewTypePinned(int viewType) {
            return viewType == Training.SECTION;
        }
    }

	@SuppressWarnings("unused")
	private static class Training {
		public static final int ITEM = 0;
		public static final int SECTION = 1;
		public int sectionNumber;
		public int sectionPosition;
		public int listPosition;
		
		public final int type;
		public final String label;
		public final String formation;
		public final String school;
		public final String place;
		public final String dates;
		public final String link;
		public final String linkDisplay;
		public final String resume;
		
		public Training(int type, String label, 
				String formation, String school, String place, String dates, String link, String linkDisplay, String resume) {
		    this.type = type;
		    this.label = label;
		    this.formation = formation;
		    this.school = school;
		    this.place = place;
		    this.dates = dates;
		    this.link = link;
		    this.linkDisplay = linkDisplay;
		    this.resume = resume;
		}
		@Override 
		public String toString() {
			return label;
		}
	}
	
	
	  ///////////////
	 // LISTENERS //
	///////////////
	
	private static class OnMoreDetailsClickListener implements OnClickListener {
		private final int fromID;
		public OnMoreDetailsClickListener(int fromID) {
			this.fromID = fromID;
		}
		@Override
		public void onClick(View v) {
			Intent detailsIntent = new Intent(fragmentController, DetailsActivity.class);
			int labelsArrayID = -1;
			int[] itemsArraysID = null;
			int colorID = -1;
			int activityNameID = -1;
    		switch(fromID) {
	    		case SECTION_MASTER: {
	    			labelsArrayID = R.array.trainings_details_sections_labels;
	    			itemsArraysID = new int[2];
	    			itemsArraysID[0] = R.array.trainings_details_master_first_year;
	    			itemsArraysID[1] = R.array.trainings_details_master_second_year;
	    			colorID = R.color.pinnedheader_head_green;
	    			activityNameID = R.string.activity_training_details_master;
		    		} break;
	    		case SECTION_LICENCE: {
	    			labelsArrayID = -1;
	    			itemsArraysID = new int[1];
	    			itemsArraysID[0] = R.array.trainings_details_licence_first_year;
	    			colorID = R.color.pinnedheader_head_blue;
	    			activityNameID = R.string.activity_training_details_licence;
	    			} break;
	    		case SECTION_DUT: {
	    			labelsArrayID = R.array.trainings_details_sections_labels;
	    			itemsArraysID = new int[2];
	    			itemsArraysID[0] = R.array.trainings_details_dut_first_year;
	    			itemsArraysID[1] = R.array.trainings_details_dut_second_year;
	    			colorID = R.color.pinnedheader_head_violet;
	    			activityNameID = R.string.activity_training_details_dut;
		    		} break;
	    		case SECTION_BAC: {
	    			labelsArrayID = -1;
	    			itemsArraysID = new int[1];
	    			itemsArraysID[0] = R.array.trainings_details_lycee_first_year;
	    			colorID = R.color.pinnedheader_head_red;
	    			activityNameID = R.string.activity_training_details_bac;
	    			} break;
    		}
			detailsIntent.putExtra("labelsArrayID", labelsArrayID);
			detailsIntent.putExtra("itemsArraysID", itemsArraysID);
			detailsIntent.putExtra("colorID", colorID);
			detailsIntent.putExtra("activityNameID", activityNameID);
    		fragmentController.startActivity(detailsIntent);
		}
	};
	
	
	private static class OnProjectsClickListener implements OnClickListener {
		private final int fromID;
		public OnProjectsClickListener(int fromID) {
			this.fromID = fromID;
		}
		@Override
		public void onClick(View v) {
			Intent detailsIntent = new Intent(fragmentController, DetailsActivity.class);
			int labelsArrayID = -1;
			int[] itemsArraysID = null;
			int colorID = -1;
			int activityNameID = -1;
    		switch(fromID) {
	    		case SECTION_MASTER: {
	    			labelsArrayID = R.array.trainings_projects_sections_labels;
	    			itemsArraysID = new int[2];
	    			itemsArraysID[0] = R.array.trainings_projects_master_first_year;
	    			itemsArraysID[1] = R.array.trainings_projects_master_second_year;
	    			colorID = R.color.pinnedheader_head_green;
	    			activityNameID = R.string.activity_training_projects_master;
		    		} break;
	    		case SECTION_LICENCE: {
	    			labelsArrayID = -1;
	    			itemsArraysID = new int[1];
	    			itemsArraysID[0] = R.array.trainings_projects_licence_first_year;
	    			colorID = R.color.pinnedheader_head_blue;
	    			activityNameID = R.string.activity_training_projects_licence;
	    			} break;
	    		case SECTION_DUT: {
	    			labelsArrayID = R.array.trainings_projects_sections_labels;
	    			itemsArraysID = new int[2];
	    			itemsArraysID[0] = R.array.trainings_projects_dut_first_year;
	    			itemsArraysID[1] = R.array.trainings_projects_dut_second_year;
	    			colorID = R.color.pinnedheader_head_violet;
	    			activityNameID = R.string.activity_training_projects_dut;
		    		} break;
	    		case SECTION_BAC: {
	    			labelsArrayID = -1;
	    			itemsArraysID = new int[1];
	    			itemsArraysID[0] = R.array.trainings_projects_lycee_first_year;
	    			colorID = R.color.pinnedheader_head_red;
	    			activityNameID = R.string.activity_training_projects_bac;
	    			} break;
    		}
			detailsIntent.putExtra("labelsArrayID", labelsArrayID);
			detailsIntent.putExtra("itemsArraysID", itemsArraysID);
			detailsIntent.putExtra("colorID", colorID);
			detailsIntent.putExtra("activityNameID", activityNameID);
			detailsIntent.putExtra("needResult", true);
			detailsIntent.putExtra("sectionID", fromID);
			mLocalContext.startActivityForResult(detailsIntent, REQUEST_PROJECT_DETAILS);
		}
	};
	
	
	private static class OnResumeSpoilerClickListener implements OnClickListener {
		private final ImageView arrowView;
		private final TextView spoilerView;
		private final TextView resumeView;
		public OnResumeSpoilerClickListener(ImageView arrowView, TextView spoilerView, TextView resumeView) {
			this.arrowView = arrowView;
			this.spoilerView = spoilerView;
			this.resumeView = resumeView;
		}
		@Override
		public void onClick(View v) {
			if(resumeView.getVisibility() == View.GONE) {
				spoilerView.setText(fragmentController.getResources().getString(R.string.hide_training_resume));
				arrowView.setImageDrawable(fragmentController.getResources().getDrawable(R.drawable.ic_arrow_to_bottom));
				resumeView.setVisibility(View.VISIBLE);
			} else {
				spoilerView.setText(fragmentController.getResources().getString(R.string.display_training_resume));
				arrowView.setImageDrawable(fragmentController.getResources().getDrawable(R.drawable.ic_arrow_to_right));
				resumeView.setVisibility(View.GONE);
			}
		}
	};
	
}
